package com.system.cacheClient.client.impl;

import com.system.cacheClient.client.ListCacheClient;
import com.system.cacheClient.feign.ListCacheFeignClient;
import com.system.cacheClient.common.CacheR;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * List缓存客户端实现类
 * 实现List类型的特殊操作方法，直接与服务端交互，不经过本地缓存
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ListCacheClientImpl implements ListCacheClient {
    
    /**
     * Feign客户端，用于与服务端通信
     */
    private final ListCacheFeignClient listCacheFeignClient;
    
    @Override
    public <T> CacheR<T> lpop(String key) {
        return listCacheFeignClient.lpop(key);
    }

    @Override
    public <T> CacheR<T> rpop(String key) {
        return listCacheFeignClient.rpop(key);
    }
    
    @Override
    public CacheR<List<String>> lrange(String key, long start, long end) {
        CacheR<List<String>> result = listCacheFeignClient.get(key);
        if (result.getCode() == 200 && result.getData() != null) {
            List<String> subList = result.getData().subList(
                (int) Math.max(0, start), 
                (int) Math.min(result.getData().size(), end + 1)
            );
            return CacheR.success(subList, "获取列表范围成功");
        }
        return CacheR.fail("获取列表范围失败");
    }

    @Override
    public CacheR<Long> llen(String key) {
        CacheR<List<String>> result = listCacheFeignClient.get(key);
        if (result.getCode() == 200 && result.getData() != null) {
            long size = result.getData().size();
            return CacheR.success(size, "获取列表长度成功");
        }
        return CacheR.fail(0L, "获取列表长度失败");
    }
}